package com.lohika.vvrublevskyy.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Component;

import com.lohika.vvrublevskyy.dao.UserDao;
import com.lohika.vvrublevskyy.dao.impl.mapers.UserRowMaper;
import com.lohika.vvrublevskyy.model.User;
import org.springframework.stereotype.Repository;

@Repository
public class JdbcDaoImpl implements UserDao {

	private NamedParameterJdbcTemplate jdbcTemplate;

	@Resource(name = "dataSource")
	public void setDataSource(DataSource dataSource) {
		jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
	}

	@Override
	public long create(User user) {
		
		KeyHolder keyHolder = new GeneratedKeyHolder();

		String sql = "INSERT INTO users (username,password,name) VALUES (:username, :password, :name)";
		
		jdbcTemplate.update(sql, new UserRowMaper().getMap(user), keyHolder);
		
		return keyHolder.getKey().longValue();
	}
	
	@Override
	public User read(long id) {
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("ID", id);
		String sql = "SELECT * FROM users WHERE id = :ID";
		List<User> users = jdbcTemplate.query(sql, parameters, new UserRowMaper()); //TODO: add factory method
		return users.isEmpty() ?  null : users.get(0);
	}


	@Override
	public List<User> getAll() {
		String sql = "SELECT * FROM users";
		return (List<User>) jdbcTemplate.query(sql, new MapSqlParameterSource(),  new UserRowMaper());
	}
	
	@Override
	public void update(User user) {
		KeyHolder keyHolder = new GeneratedKeyHolder();
		
		String sql = "UPDATE users SET username = :username, password = :password,  name = :name  WHERE id = :ID";
		
		jdbcTemplate.update(sql, new UserRowMaper().getMap(user), keyHolder);
	}

	@Override
	public void delete(long id) {
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("ID", id);
		
		String sql = "DELETE FROM users WHERE id=:ID";
		jdbcTemplate.update(sql, new MapSqlParameterSource(parameters));
	}


}
